import { Document, Model, ObjectId } from 'mongoose'
import mongoose from './mongoose'
import lastModifiedPlugin from './mongoosePlugins/lastModPlugin'

const Types = mongoose.Schema.Types

export class VersionModel {
  id?: ObjectId
  versionName: string
  createTime?: Date
  latest?: Number
}

const version = new mongoose.Schema({
  id: Types.ObjectId,
  versionName: {
    type: Types.String,
    required: true,
    unique: true,
    index: 1
  },
  createTime: {
    type: Types.Date,
    default: Date.now,
    index: 1
  },
  latest: {
    type: Types.Number,
    required: true,
    index: 1,
    default: 0 // 0: latest
  }
})

version.plugin(lastModifiedPlugin)

const versionTableMap = new Map<string, Model<Document>>()

export default function getVersionModel (versionTableName: string): Model<Document> {
  if (versionTableMap.has(versionTableName)) {
    return versionTableMap.get(versionTableName)
  } else {
    versionTableMap.set(versionTableName, mongoose.model(versionTableName, version, versionTableName))
    return getVersionModel(versionTableName)
  }
}
